package com.cloud.service.impl;

import com.cloud.service.GarageService;
import com.cloud.dao.GarageDao;
import com.cloud.dto.GarageDto;
import com.cloud.model.Garage;
import com.cloud.enums.ResultEnum;
import com.cloud.exception.BusinessException;
import com.cloud.util.BeanUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * Created by util on 2018-4-27.
 */
@Service
public class GarageServiceImpl implements GarageService {

    @Autowired
    private GarageDao garageDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean insertGarage(GarageDto garageDto){
    	Garage garage = new Garage();
    	BeanUtil.copyProperties(garageDto, garage);
        int num = garageDao.insertGarage(garage);
        success(num);
        return true;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteGarage(GarageDto garageDto){
    	Garage garage = new Garage();
    	BeanUtil.copyProperties(garageDto, garage);
        int num = garageDao.deleteGarage(garage);
        success(num);
        return true;
    }

	private void success(int num) {
        if (num != 1) {
            throw new BusinessException(ResultEnum.fail);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateGarage(GarageDto garageDto){
    	Garage garage = new Garage();
    	BeanUtil.copyProperties(garageDto, garage);
        int num = garageDao.updateGarage(garage);
        success(num);
        return true;
    }
    
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Garage selectGarageById(GarageDto garageDto){
        Garage garage = garageDao.selectGarageById(garageDto.getId());
        if (garage == null) {
        	return new Garage();
        }
        return garage;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public List<Garage> selectGarageList(GarageDto garageDto){
    	Garage garage = new Garage();
    	BeanUtil.copyProperties(garageDto, garage);
        return garageDao.selectGarageList(garage);
    }
    
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public PageInfo selectGaragePage(GarageDto garageDto){
    	Garage garage = new Garage();
    	BeanUtil.copyProperties(garageDto, garage);
        return garageDao.selectGaragePage(garage, garageDto.getPageNum(), garageDto.getPageSize());
    }

}